import { create } from 'zustand'
import { videoService, audioService } from '@/services'
import { useLoadingStore } from '@/stores/loading-store'
import { toast } from '@/hooks/use-toast'
import { type GraphicCreationConfig } from '@/services'
import { sleep } from '@/lib/utils'
import { pollingTaskResult } from '@/stores/video'

export interface Option {
  label: string
  value: string
  label_zh?: string
}

interface CustomError extends Error {
  code?: string
}

interface PictureItem {
  parentId: string
  id: string
  status: string
  msg: string
  type: string
  url: string
}

export interface AudioDataItem {
  id: number
  label: string
  value: number
  file_id: string
  file_url: string
}

interface GraphicState {
  createdText: string
  pictureList: PictureItem[]
  createdId: string
  // 系统配置
  systemConfig: GraphicCreationConfig
  setPictureList: (data: PictureItem[]) => void
  setCreatedId: (text: string) => void
  fetchSystemConfig: () => Promise<void>
  getBroadcastDetail: (id: string) => Promise<string>
  // 重置状态
  resetState: () => void
  getGraphicTextDetail: (id: string) => Promise<string>
  graphicCreationDetail: (id: string) => void
  getGraphicPictureDetail: (data: {
    id: string
    picture_id: string
  }) => Promise<void>
}

const defInitialState = {
  createdText: '',
  pictureList: [],
  createdId: '',
  systemConfig: {
    pictureType: [],
    pictureStyle: [],
    officalAccountOrientation: [],
  },
}

// 创建 store
export const useGraphicStore = create<GraphicState>()((set, get) => ({
  ...defInitialState,
  // 重置状态
  resetState: () => {
    set({ ...defInitialState })
  },
  setPictureList: (data: PictureItem[]) => {
    set({ pictureList: data })
  },
  setCreatedId: (textId: string) => {
    set({ createdId: textId })
  },
  fetchSystemConfig: async () => {
    try {
      // 图文创作配置
      if (get().systemConfig.pictureType.length > 0) {
        return
      }
      const res = await videoService.getGraphicCreationConfig()
      set({
        systemConfig: {
          pictureType: res.pictureType,
          pictureStyle: res.pictureStyle,
          officalAccountOrientation: res.officalAccountOrientation,
        },
      })
    } catch (error) {
      console.error(error)
    }
  },

  // 轮询获取文案任务详情
  getBroadcastDetail: async (id: string): Promise<string> => {
    const waitTaskResult = async (): Promise<{
      textId: string
      pictureId: string
    }> => {
      // 循环调用来查看状态结果
      let result = false
      let count = 0
      const maxCount = 1350 // 最多轮询30次
      const waitTime = 2000
      let textId = null
      let pictureId = null

      while (!result && count < maxCount) {
        await sleep(waitTime)
        const res = await audioService.graphicCreationDetail(id)
        console.log('🚀 ~ graphicCreationDetail ~ res:', res)
        result = res.status === 'finish'
        // 文字状态
        const tipsWord = res.result.msg
        useLoadingStore.getState().setLoadingMessage(tipsWord)
        if (res.status.includes('error')) {
          toast({
            variant: 'destructive',
            description: '生成图文出错' + res.status,
            duration: Infinity,
          })
          const cusError = new Error('生成图文出错') as CustomError
          cusError['code'] = 'CUS_ERROR'
          throw cusError
        }
        if (result) {
          textId = res.graphic_creation_offical_account_texts[0]?.id
          pictureId = res.graphic_creation_offical_account_pictures[0]?.id
          console.log('获取到结果了')
          break
        }
        count++
      }
      return {
        textId: textId || '',
        pictureId: pictureId || '',
      }
    }
    // 再轮询，查图片并查文字
    const waitTextPicutreTask = async (
      textId: string,
      pictureId: string,
    ): Promise<{
      text: string
      picture: any[]
    }> => {
      // 循环调用来查看状态结果
      const textResult = {
        status: false,
        data: '', // 文本内容
      }
      const pictureResult = {
        status: false,
        data: [], // 图片内容
      }
      let count = 0
      const maxCount = 1350 // 最多轮询30次
      const waitTime = 2000

      while (!(textResult.status && pictureResult.status) && count < maxCount) {
        await sleep(waitTime)
        console.log('再轮询，查图片并查文字...')
        const textPromise =
          textId && !textResult.status
            ? audioService.graphicTextDetail(textId)
            : Promise.resolve({ status: 'finish' } as {
                status: string
                result: any
              })
        const picturePromise =
          pictureId && !pictureResult.status
            ? audioService.graphicPictureDetail(pictureId)
            : Promise.resolve({ status: 'finish' } as {
                status: string
                result: any
              })
        // 再轮询，查图片并查文字
        const [textRes, pictureRes] = await Promise.all([
          textPromise,
          picturePromise,
        ])
        console.log('🚀 ~ getBroadcastDetail ~ textRes:', textRes)
        console.log('🚀 ~ getBroadcastDetail ~ pictureRes:', pictureRes)

        if (!textResult.status && textRes.status === 'finish') {
          textResult.status = true
          textResult.data = textRes.result.data
          set({ createdText: textRes.result.data })
        }
        if (!pictureResult.status && pictureRes.status === 'finish') {
          pictureResult.status = true
          console.log('pictureRes.result.data:', pictureRes?.result?.data)
          pictureResult.data = pictureRes?.result?.data
          if (Array.isArray(pictureResult.data)) {
            pictureResult.data.forEach((item: PictureItem) => {
              item.parentId = pictureId
            })
          }
          // parentId
          set({ pictureList: pictureResult.data as PictureItem[] })
        }
        // 文字状态
        const tipsWord = !textResult.status
          ? textRes.result?.msg
          : pictureRes.result?.msg

        useLoadingStore.getState().setLoadingMessage(tipsWord)
        if (textRes.status.includes('error')) {
          toast({
            variant: 'destructive',
            description: '生成图文出错' + textRes.status,
            duration: Infinity,
          })
          const cusError = new Error('生成图文出错') as CustomError
          cusError['code'] = 'CUS_ERROR'
          throw cusError
        }
        if (pictureRes.status.includes('error')) {
          toast({
            variant: 'destructive',
            description: '生成图文出错' + pictureRes.status,
            duration: Infinity,
          })
          const cusError = new Error('生成图文出错') as CustomError
          cusError['code'] = 'CUS_ERROR'
          throw cusError
        }
        count++
      }

      return {
        text: textResult.data,
        picture: pictureResult.data,
      }
    }
    const text = ''
    try {
      useLoadingStore.getState().increment()
      const { textId, pictureId } = await waitTaskResult()
      set({ createdId: textId })
      const resultText = await waitTextPicutreTask(textId, pictureId)
      console.log('🚀 ~ resultText:', resultText)
      useLoadingStore.getState().decrement()
    } catch (error: any) {
      console.error('🚀 ~ getBroadcastDetail: ~ error:', error)
      if (error?.code !== 'CUS_ERROR') {
        toast({
          variant: 'destructive',
          description: '出错了: ' + error,
          duration: Infinity,
        })
      }
      useLoadingStore.getState().decrement()
    }
    return text
  },
  // 历史记录
  getHistoryList: async (id: string) => {
    return await videoService.videoCreationDetail(id).then((res) => {
      console.log('res:', res)
    })
  },

  graphicCreationDetail: (id: string) => {
    audioService.graphicCreationDetail(id).then((res) => {
      console.log('res:', res)
    })
  },
  getGraphicTextDetail: async (id: string): Promise<string> => {
    const text =
      (await pollingTaskResult({
        id,
        isRefresh: true,
        reloadServiceCopy: audioService.graphicTextDetailReload,
        getServiceDetail: audioService.graphicTextDetail,
        errorMessage: '生成文案出错',
      })) ?? ''
    return text as string
  },
  // 重新生成图片任务
  getGraphicPictureDetail: async ({
    id,
    picture_id,
  }: {
    id: string
    picture_id: string
  }): Promise<void> => {
    const result =
      (await pollingTaskResult({
        id,
        isRefresh: true,
        reloadServiceCopy: async (_id: string) => {
          return audioService.reloadPicture({ id, picture_id: picture_id })
        },
        getServiceDetail: (_id) => {
          return audioService.graphicPictureDetail(id)
        },
        errorMessage: '重新生成图片出错',
      })) ?? []

    console.log('result:', result)
    if (Array.isArray(result)) {
      result.forEach((item) => {
        item.parentId = id
      })
    }
    set({ pictureList: result as PictureItem[] })
    // return text as string
  },
}))
